<template>
  <div class="form-design-box">
    <div class="design-main">
      <iframe
        v-if="iframeSrc"
        ref="iframeRef"
        :src="iframeSrc"
        allowfullscreen="true"
        webkitallowfullscreen="true"
        mozallowfullscreen="true"
        frameborder="0"
        style="width: 100%; height: 100%"
        @load="loaded"
      ></iframe>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { getToken } from "@/utils/auth";
const router = useRouter();
const route = useRoute();
const { type, id, name } = route.query;
const iframeSrc = `http://203.33.215.198:9081/#/designForm?id=${id}&token=${encodeURIComponent(getToken())}`;
const iframeRef = ref();
onMounted(async () => {
  // 在外部vue的window上添加postMessage的监听，并且绑定处理函数handleMessage
  window.addEventListener("message", handleMessage);
});

const handleMessage = (event) => {
  console.log("handleMessage", event);
  // 根据上面制定的结构来解析iframe内部发回来的数据
  const data = JSON.parse(event.data);
  const { cwd } = data;
  if (cwd == "back" || cwd == "save") {
    router.go(-1);
  }
};

onBeforeUnmount(() => {
  window.removeEventListener("message", handleMessage);
});

const loaded = () => {
  console.log("loaded");
  const { id, name } = route.query;
  // iframe 加载时传递数据给子组件
  if (iframeRef.value) {
    console.log("向子级传值");
    iframeRef.value.contentWindow.postMessage(
      {
        cwd: "sendMsg",
        params: {
          name,
          id,
        },
      },
      "*"
    );
  }
};
</script>

<style lang="less" scoped>
.form-design-box {
  width: 100%;
  height: 100%;
  overflow: hidden;

  .fd-nav {
    position: fixed;
    top: 4px;
    left: 100px;
    z-index: 1;

    .back {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: var(--color-text-2);
      background-color: var(--color-secondary);
      font-size: 14px;
      border-radius: var(--border-radius-small);

      &:hover {
        background-color: var(--color-secondary-hover);
      }
    }
  }

  .design-main {
    width: 100%;
    height: 100%;
  }
}
</style>
